package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.ErrorConstants;
import com.ruoyi.common.core.domain.BaseDto;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.dao.TAbnormalDataDao;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.domain.po.*;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.BlsService;
import com.ruoyi.system.service.PmsArchivesService;
import com.ruoyi.system.service.QuaControlService;
import org.jetbrains.annotations.TestOnly;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.ruoyi.common.constant.UserConstants.QuestionCode.*;

@Service
public class QuaControlImpl implements QuaControlService {

    @Resource
    private QuaAbnormalDataRuleMapper quaAbnormalDataRuleMapper;
    @Resource
    private TAbnormalDataDao abnormalDataDao;
    @Resource
    private QuaAbnormalDataMapper quaAbnormalDataMapper;
    @Resource
    private QuaAbnormalDataRecordMapper quaAbnormalDataRecordMapper;
    @Resource
    private QuaControlRuleMapper quaControlRuleMapper;
    @Resource
    private PmsArchivesService archivesService;
    @Resource
    private BlsService blsService;

    @Override
    public void addRule(AbnormalDataDto.AbnoRuleInsert dto) {
        TopTopic topTopic = BeanUtil.copyProperties(dto, TopTopic.class);
        Long id = dto.getId();
        if (id == null) {
            topTopic.setId(IdUtil.getSnowflake().nextId());
            topTopic.setCreateTime(new Date());
            topTopic.setCreateBy(SecurityUtils.getUsername());
            topTopic.setDelFlag((byte) 0);
        } else {
            topTopic.setUpdateTime(new Date());
            topTopic.setUpdateBy(SecurityUtils.getUsername());
        }
    }

    @Override
    public void delRule(AbnormalDataDto.RuleDelete dto) {
        TopTopicExample topTopicExample = new TopTopicExample();
        topTopicExample.createCriteria().andIdIn(dto.getIdList());
        TopTopic topTopic = new TopTopic();
        topTopic.setDelFlag((byte) 0);
    }

    @Override
    public List<AbnormalDataVo.AbnoRuleResult> queryRule(AbnormalDataDto.RuleQuery dto) {
        return null;
    }

    @Override
    public void addDataRule(AbnormalDataDto.RuleInsert dto) {
        QuaAbnormalDataRule quaAbnormalDataRule = BeanUtil.copyProperties(dto, QuaAbnormalDataRule.class);
        if (quaAbnormalDataRule.getId() == null) {
            quaAbnormalDataRule.setId(IdUtil.getSnowflake().nextId());
            quaAbnormalDataRule.setCreateBy(SecurityUtils.getUsername());
            quaAbnormalDataRule.setDelFlag((byte) 0);
            quaAbnormalDataRule.setCreateTime(new Date());
            quaAbnormalDataRuleMapper.insertSelective(quaAbnormalDataRule);
        } else {
            quaAbnormalDataRule.setUpdateBy(SecurityUtils.getUsername());
            quaAbnormalDataRule.setDelFlag((byte) 0);
            quaAbnormalDataRule.setUpdateTime(new Date());
            quaAbnormalDataRuleMapper.updateByPrimaryKeySelective(quaAbnormalDataRule);
        }
    }

    @Override
    public void delDataRule(AbnormalDataDto.RuleDelete dto) {
        QuaAbnormalDataRuleExample quaAbnormalDataRuleExample = new QuaAbnormalDataRuleExample();
        quaAbnormalDataRuleExample.createCriteria().andIdIn(dto.getIdList());
        QuaAbnormalDataRule quaAbnormalDataRule = new QuaAbnormalDataRule();
        quaAbnormalDataRule.setDelFlag((byte) 1);
        quaAbnormalDataRuleMapper.updateByExampleSelective(quaAbnormalDataRule, quaAbnormalDataRuleExample);
    }

    @Override
    public List<AbnormalDataVo.RuleResult> queryDataRule(AbnormalDataDto.RuleQuery dto) {
        return abnormalDataDao.queryAbnormalDataRule(dto.getName());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer insertAbnormalData(TAbnormalDataDto.Insert abnormalDataInsert) {
        // 新增实体数据
        long abnormalDataId = IdUtil.getSnowflake().nextId();
        QuaAbnormalData abnormalData = BeanUtil.copyProperties(abnormalDataInsert, QuaAbnormalData.class);
        abnormalData.setId(abnormalDataId);
        abnormalData.setCreateBy(SecurityUtils.getUsername());
        abnormalData.setCreateTime(new Date());
        int i = quaAbnormalDataMapper.insertSelective(abnormalData);
        // 新增子表数据
        List<TAbnormalDataDto.AbnormalDataRecordDto> recordDtoList = abnormalDataInsert.getRecordDtoList();
        if (i > 0 && !recordDtoList.isEmpty()) {
            recordDtoList.forEach(recordDto -> {
                QuaAbnormalDataRecord abnormalDataRecord = BeanUtil.copyProperties(recordDto, QuaAbnormalDataRecord.class);
                abnormalDataRecord.setId(IdUtil.getSnowflake().nextId());
                abnormalDataRecord.setAbnormalId(abnormalDataId);
                abnormalDataRecord.setCreatedAt(new Date());
                quaAbnormalDataRecordMapper.insertSelective(abnormalDataRecord);
            });
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateAbnormalData(TAbnormalDataDto.Update abnormalDataUpdate) {
        // 修改实体
        QuaAbnormalData abnormalData = BeanUtil.copyProperties(abnormalDataUpdate, QuaAbnormalData.class);
        abnormalData.setUpdateBy(SecurityUtils.getUsername());
        abnormalData.setUpdateTime(new Date());
        int i = quaAbnormalDataMapper.updateByPrimaryKeySelective(abnormalData);
        if (i > 0 && !abnormalDataUpdate.getRecordDtoList().isEmpty()) {
            abnormalDataUpdate.getRecordDtoList().forEach(recordDto -> {
                QuaAbnormalDataRecord abnormalDataRecord = BeanUtil.copyProperties(abnormalDataUpdate.getRecordDtoList(), QuaAbnormalDataRecord.class);
                abnormalDataRecord.setUpdatedAt(new Date());
                QuaAbnormalDataRecordExample abnormalDataRecordExample = new QuaAbnormalDataRecordExample();
                abnormalDataRecordExample.createCriteria().andCodeEqualTo(recordDto.getCode()).andAbnormalIdEqualTo(abnormalDataUpdate.getId());
                quaAbnormalDataRecordMapper.updateByExampleSelective(abnormalDataRecord, abnormalDataRecordExample);
            });
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer deleteAbnormalData(TAbnormalDataDto.Delete TAbnormalDataDelete) {
        QuaAbnormalDataExample abnormalDataExample = new QuaAbnormalDataExample();
        abnormalDataExample.createCriteria().andIdIn(TAbnormalDataDelete.getIdList());
        QuaAbnormalData abnormalData = new QuaAbnormalData();
        abnormalData.setDelFlag((byte) 2);
        int i = quaAbnormalDataMapper.updateByExampleSelective(abnormalData, abnormalDataExample);
        if (i > 0) {
            QuaAbnormalDataRecordExample abnormalDataRecordExample = new QuaAbnormalDataRecordExample();
            abnormalDataRecordExample.createCriteria().andAbnormalIdIn(TAbnormalDataDelete.getIdList());
            QuaAbnormalDataRecord abnormalDataRecord = new QuaAbnormalDataRecord();
            abnormalDataRecord.setDelFlag((byte) 2);
            quaAbnormalDataRecordMapper.updateByExampleSelective(abnormalDataRecord, abnormalDataRecordExample);
        }
        return i;
    }

    @Override
    public List<BlsVo.BlsZlInfoVo> listAbnormalData(BaseDto<TAbnormalDataDto.Query> list) throws ParseException {

        List<QuaAbnormalData> quaAbnormalDataRecords = quaAbnormalDataMapper.selectByExample(new QuaAbnormalDataExample());

        if (CollectionUtil.isEmpty(quaAbnormalDataRecords)) {
            return Collections.emptyList();
        }

        BaseDto<PmsArchivesDto.Query> baseDto = new BaseDto<>();
        PmsArchivesDto.Query query = new PmsArchivesDto.Query();
        query.setIdList(quaAbnormalDataRecords.stream().map(QuaAbnormalData::getBlsId).collect(Collectors.toList()));
        baseDto.setParam(query);
        BlsDto.Query query1 = new BlsDto.Query();
        PageHelper.startPage(list.getPageNum(), list.getPageSize());
        query1.setIdList(quaAbnormalDataRecords.stream().map(QuaAbnormalData::getBlsId).collect(Collectors.toList()));
        List<BlsVo.BlsZlInfoVo> infoList = blsService.queryZl(query1);

        //根据ID查询档案
//        PageInfo<PmsArchivesVo.Result> pmsArchive = archivesService.listPmsArchive(baseDto);
//        List<PmsArchivesVo.Result> infoList = pmsArchive.getList();
        if (CollectionUtil.isNotEmpty(infoList)) {
            for (BlsVo.BlsZlInfoVo result : infoList) {
                Integer dnt = result.getDnt();
                Integer ont = result.getOnt();
                Integer dpt = result.getDpt();
                Integer opt = result.getOpt();
                Integer prt = result.getPrt();

                Integer dit = result.getDit();
//                if (CollectionUtil.isNotEmpty(zbRuleResultList)) {
//                    List<BlsVo.BlsJzInfoVo.PmsArchivesRecordVo> recordVoList = result.getRecordVoList();
//                    Map<String, AbnormalDataVo.RuleResult> zbMap = zbRuleResultList.stream().collect(Collectors.toMap(AbnormalDataVo.RuleResult::getName, Function.identity()));
//                    AbnormalDataVo.RuleResult dntRuleResult = zbMap.get("DNT");
//                    if (dnt != null && dntRuleResult != null) {
//                        BlsVo.BlsJzInfoVo.PmsArchivesRecordVo recordVo = new BlsVo.BlsJzInfoVo.PmsArchivesRecordVo();
//                        Integer maxValue = dntRuleResult.getMaxData();
//                        Integer minValue = dntRuleResult.getMinValue();
//                        recordVo.setCode("DNT");
//                        recordVo.setAnswer(dpt + "");
//                        if (maxValue < dnt || minValue > dnt) {
//                            recordVo.setIsAbnormal((byte) 1);
//                        } else {
//                            recordVo.setIsAbnormal((byte) 0);
//                        }
//                        recordVo.setNormal(minValue + " - " + maxValue);
//                        recordVoList.add(recordVo);
//                    }
//                    AbnormalDataVo.RuleResult ontRuleResult = zbMap.get("ONT");
//                    if (ont != null && ontRuleResult != null) {
//                        BlsVo.BlsJzInfoVo.PmsArchivesRecordVo recordVo = new BlsVo.BlsJzInfoVo.PmsArchivesRecordVo();
//                        Integer maxValue = ontRuleResult.getMaxData();
//                        Integer minValue = ontRuleResult.getMinValue();
//                        recordVo.setCode("ONT");
//                        recordVo.setAnswer(ont + "");
//                        if (maxValue < ont || minValue > ont) {
//                            recordVo.setIsAbnormal((byte) 1);
//                        } else {
//                            recordVo.setIsAbnormal((byte) 0);
//                        }
//                        recordVo.setNormal(minValue + " - " + maxValue);
//                        recordVoList.add(recordVo);
//                    }
//                    AbnormalDataVo.RuleResult dptRuleResult = zbMap.get("DPT");
//                    if (dpt != null && dptRuleResult != null) {
//                        Integer maxValue = dptRuleResult.getMaxData();
//                        Integer minValue = dptRuleResult.getMinValue();
//                        BlsVo.BlsJzInfoVo.PmsArchivesRecordVo recordVo = new BlsVo.BlsJzInfoVo.PmsArchivesRecordVo();
//                        recordVo.setCode("DPT");
//                        recordVo.setAnswer(ont + "");
//                        if (maxValue < dpt || minValue > dpt) {
//                            recordVo.setIsAbnormal((byte) 1);
//                        } else {
//                            recordVo.setIsAbnormal((byte) 0);
//                        }
//                        recordVo.setNormal(minValue + " - " + maxValue);
//                        recordVoList.add(recordVo);
//                    }
//                    AbnormalDataVo.RuleResult ditRuleResult = zbMap.get("DIT");
//                    if (dit != null && ditRuleResult != null) {
//                        BlsVo.BlsJzInfoVo.PmsArchivesRecordVo recordVo = new BlsVo.BlsJzInfoVo.PmsArchivesRecordVo();
//                        recordVo.setCode("DIT");
//                        recordVo.setAnswer(dit + "");
//                        recordVoList.add(recordVo);
//                    }
//                    AbnormalDataVo.RuleResult prtRuleResult = zbMap.get("PRT");
//                    if (prt != null && prtRuleResult != null) {
//                        BlsVo.BlsJzInfoVo.PmsArchivesRecordVo recordVo = new BlsVo.BlsJzInfoVo.PmsArchivesRecordVo();
//                        Integer maxValue = prtRuleResult.getMaxData();
//                        Integer minValue = prtRuleResult.getMinValue();
//                        recordVo.setCode("PRT");
//                        recordVo.setAnswer(prt + "");
//                        if (maxValue < prt || minValue > prt) {
//                            recordVo.setIsAbnormal((byte) 1);
//                        } else {
//                            recordVo.setIsAbnormal((byte) 0);
//                        }
//                        recordVo.setNormal(minValue + " - " + maxValue);
//                        recordVoList.add(recordVo);
//                    }
//
//                    Map<String, List<BlsVo.BlsJzInfoVo.PmsArchivesRecordVo>> recordMap = recordVoList.stream().collect(Collectors.groupingBy(BlsVo.BlsJzInfoVo.PmsArchivesRecordVo::getCode));
//                    //必填异常校验
//                    if (CollectionUtil.isNotEmpty(ruleResults)) {
//                        for (AbnormalDataVo.RuleResult ruleResult : ruleResults) {
//                            if (CollectionUtil.isNotEmpty(recordMap.get(ruleResult.getName()))) {
//                                if (StrUtil.isEmpty(recordMap.get(ruleResult.getName()).get(0).getAnswer())) {
//                                    recordMap.get(ruleResult.getName()).get(0).setIsAbnormal((byte) 0);
//                                    recordMap.get(ruleResult.getName()).get(0).setIsMust((byte) 0);
//                                } else {
//                                    recordMap.get(ruleResult.getName()).get(0).setIsMust((byte) 0);
//                                }
//                            } else {
//                                BlsVo.BlsJzInfoVo.PmsArchivesRecordVo recordVo = new BlsVo.BlsJzInfoVo.PmsArchivesRecordVo();
//                                recordVo.setIsAbnormal((byte) 1);
//                                recordVo.setCode(ruleResult.getName());
//                                recordVo.setIsMust((byte) 0);
//                                recordVoList.add(recordVo);
//                            }
//                        }
//                    }
//                    result.setRecordVoList(recordVoList);
//                }
            }
        }
        return infoList;
    }

    @Override
    public PmsArchivesVo.Detail detailAbnormalData(BaseDto<TAbnormalDataDto.Query> list) {
        List<Long> patientIdList = new ArrayList<>();
        //1. 查询异常规则
        List<AbnormalDataVo.RuleResult> ruleResultList = queryDataRule(new AbnormalDataDto.RuleQuery());
        if (CollectionUtil.isEmpty(ruleResultList)) {
            throw new BaseException(ErrorConstants.ABNORMAL_DATA_RULE_NOT_FOUND);
        }
        //2. 根据异常规则查询不符合条件的code数据
        //2.1 根据类型分组
        Map<Byte, List<AbnormalDataVo.RuleResult>> map = ruleResultList.stream().collect(Collectors.groupingBy(AbnormalDataVo.RuleResult::getType));
        //必填异常
        List<AbnormalDataVo.RuleResult> ruleResults = map.get((byte) 0);

        //2.2 指标异常数据查询
        List<AbnormalDataVo.RuleResult> zbRuleResultList = map.get((byte) 1);
        if (CollectionUtil.isNotEmpty(zbRuleResultList)) {
            Map<String, AbnormalDataVo.RuleResult> zbMap = zbRuleResultList.stream().collect(Collectors.toMap(AbnormalDataVo.RuleResult::getName, Function.identity()));
            AbnormalDataVo.RuleResult dnt = zbMap.get("DNT");
            AbnormalDataVo.RuleResult ont = zbMap.get("ONT");
            AbnormalDataVo.RuleResult dpt = zbMap.get("DPT");
            AbnormalDataVo.RuleResult dit = zbMap.get("DIT");
            AbnormalDataVo.RuleResult prt = zbMap.get("PRT");
            List<Long> zbPatientIdList = abnormalDataDao.queryAbnormalData(dnt == null ? null : dnt.getMinValue(), dnt == null ? null : dnt.getMaxData(), ont == null ? null : ont.getMinValue(), ont == null ? null : ont.getMaxData(), dpt == null ? null : dpt.getMinValue(), dpt == null ? null : dpt.getMaxData(), dit == null ? null : dit.getMinValue(), dit == null ? null : dit.getMaxData(), prt == null ? null : prt.getMinValue(), prt == null ? null : prt.getMaxData());
            patientIdList.addAll(zbPatientIdList);
        }

        if (CollectionUtil.isEmpty(patientIdList)) {
            return new PmsArchivesVo.Detail();
        }
        BaseDto<PmsArchivesDto.Query> baseDto = new BaseDto<>();
        PmsArchivesDto.Query query = new PmsArchivesDto.Query();
        query.setIdList(patientIdList);
        baseDto.setParam(query);
        //根据ID查询档案
        PageInfo<PmsArchivesVo.Result> pmsArchive = archivesService.listPmsArchive(baseDto);
        List<PmsArchivesVo.Result> infoList = pmsArchive.getList();
        if (CollectionUtil.isNotEmpty(infoList)) {
            PmsArchivesVo.Detail result = BeanUtil.copyProperties(infoList.get(0), PmsArchivesVo.Detail.class);

            Integer dnt = result.getDnt();
            Integer ont = result.getOnt();
            Integer dpt = result.getDpt();
            Integer opt = result.getOpt();
            Integer prt = result.getPrt();

            Integer dit = result.getDit();
            if (CollectionUtil.isNotEmpty(zbRuleResultList)) {
                List<PmsArchivesVo.PmsArchivesRecordVo> recordVoList = result.getRecordVoList();
                Map<String, AbnormalDataVo.RuleResult> zbMap = zbRuleResultList.stream().collect(Collectors.toMap(AbnormalDataVo.RuleResult::getName, Function.identity()));
                AbnormalDataVo.RuleResult dntRuleResult = zbMap.get("DNT");
                if (dnt != null && dntRuleResult != null) {
                    PmsArchivesVo.PmsArchivesRecordVo recordVo = new PmsArchivesVo.PmsArchivesRecordVo();
                    Integer maxValue = dntRuleResult.getMaxData();
                    Integer minValue = dntRuleResult.getMinValue();
                    recordVo.setCode("DNT");
                    recordVo.setAnswer(dpt + "");
                    if (maxValue < dnt || minValue > dnt) {
                        recordVo.setIsAbnormal((byte) 1);
                    } else {
                        recordVo.setIsAbnormal((byte) 0);
                    }
                    recordVo.setNormal(minValue + " - " + maxValue);
                    recordVoList.add(recordVo);
                }
                AbnormalDataVo.RuleResult ontRuleResult = zbMap.get("ONT");
                if (ont != null && ontRuleResult != null) {
                    PmsArchivesVo.PmsArchivesRecordVo recordVo = new PmsArchivesVo.PmsArchivesRecordVo();
                    Integer maxValue = ontRuleResult.getMaxData();
                    Integer minValue = ontRuleResult.getMinValue();
                    recordVo.setCode("ONT");
                    recordVo.setAnswer(ont + "");
                    if (maxValue < ont || minValue > ont) {
                        recordVo.setIsAbnormal((byte) 1);
                    } else {
                        recordVo.setIsAbnormal((byte) 0);
                    }
                    recordVo.setNormal(minValue + " - " + maxValue);
                    recordVoList.add(recordVo);
                }
                AbnormalDataVo.RuleResult dptRuleResult = zbMap.get("DPT");
                if (dpt != null && dptRuleResult != null) {
                    Integer maxValue = dptRuleResult.getMaxData();
                    Integer minValue = dptRuleResult.getMinValue();
                    PmsArchivesVo.PmsArchivesRecordVo recordVo = new PmsArchivesVo.PmsArchivesRecordVo();
                    recordVo.setCode("DPT");
                    recordVo.setAnswer(ont + "");
                    if (maxValue < dpt || minValue > dpt) {
                        recordVo.setIsAbnormal((byte) 1);
                    } else {
                        recordVo.setIsAbnormal((byte) 0);
                    }
                    recordVo.setNormal(minValue + " - " + maxValue);
                    recordVoList.add(recordVo);
                }
                AbnormalDataVo.RuleResult ditRuleResult = zbMap.get("DIT");
                if (dit != null && ditRuleResult != null) {
                    PmsArchivesVo.PmsArchivesRecordVo recordVo = new PmsArchivesVo.PmsArchivesRecordVo();
                    recordVo.setCode("DIT");
                    recordVo.setAnswer(dit + "");
                    recordVoList.add(recordVo);
                }
                AbnormalDataVo.RuleResult prtRuleResult = zbMap.get("PRT");
                if (prt != null && prtRuleResult != null) {
                    PmsArchivesVo.PmsArchivesRecordVo recordVo = new PmsArchivesVo.PmsArchivesRecordVo();
                    Integer maxValue = prtRuleResult.getMaxData();
                    Integer minValue = prtRuleResult.getMinValue();
                    recordVo.setCode("PRT");
                    recordVo.setAnswer(prt + "");
                    if (maxValue < prt || minValue > prt) {
                        recordVo.setIsAbnormal((byte) 1);
                    } else {
                        recordVo.setIsAbnormal((byte) 0);
                    }
                    recordVo.setNormal(minValue + " - " + maxValue);
                    recordVoList.add(recordVo);
                }

                Map<String, List<PmsArchivesVo.PmsArchivesRecordVo>> recordMap = recordVoList.stream().collect(Collectors.groupingBy(PmsArchivesVo.PmsArchivesRecordVo::getCode));
                //必填异常校验
                if (CollectionUtil.isNotEmpty(ruleResults)) {
                    for (AbnormalDataVo.RuleResult ruleResult : ruleResults) {
                        if (CollectionUtil.isNotEmpty(recordMap.get(ruleResult.getName()))) {
                            if (StrUtil.isEmpty(recordMap.get(ruleResult.getName()).get(0).getAnswer())) {
                                recordMap.get(ruleResult.getName()).get(0).setIsAbnormal((byte) 0);
                                recordMap.get(ruleResult.getName()).get(0).setIsMust((byte) 0);
                            } else {
                                recordMap.get(ruleResult.getName()).get(0).setIsMust((byte) 0);
                            }
                        } else {
                            PmsArchivesVo.PmsArchivesRecordVo recordVo = new PmsArchivesVo.PmsArchivesRecordVo();
                            recordVo.setIsAbnormal((byte) 1);
                            recordVo.setCode(ruleResult.getName());
                            recordVo.setIsMust((byte) 0);
                            recordVoList.add(recordVo);
                        }
                    }
                }
                List<PmsArchivesVo.Detail.TagGroup> tagGroupList = new ArrayList<>();
                Map<Long, List<PmsArchivesVo.PmsArchivesRecordVo>> collect = recordVoList.stream().collect(Collectors.groupingBy(PmsArchivesVo.PmsArchivesRecordVo::getCodeTagId));
                for (Map.Entry<Long, List<PmsArchivesVo.PmsArchivesRecordVo>> entry : collect.entrySet()) {
                    PmsArchivesVo.Detail.TagGroup tagGroup = new PmsArchivesVo.Detail.TagGroup();
                    tagGroup.setId(entry.getKey());
                    tagGroup.setName(entry.getValue().get(0).getCodeTagName());
                    tagGroup.setRecordVoList(entry.getValue());
                    tagGroupList.add(tagGroup);
                }
                result.setTagGroupList(tagGroupList);
                result.setRecordVoList(recordVoList);
            }
            return result;
        }
        return new PmsArchivesVo.Detail();
    }

    /**
     * 异常数据标注：按照项目原型设计，标注出一些必填项未填以及ODT、DNT、DIT、ONT、DPT、PRT超出正常取值范围的异常。
     * 1.必填项包括：
     * （1）入院日期
     * （2）手术时间
     * 根据不同治疗类型在不同的tab页提示：
     * 治疗类型：静脉溶栓手术->开始静脉溶栓时间；
     * 治疗类型：介入再通->穿刺完成时间；
     * 治疗类型：脑出血手术->手术开始时间；
     * 治疗类型：CEA/CAS手术->手术开始时间。
     * （3）颅内血管检查方式（若患者治疗类型为颅内动脉瘤）
     * 2.ODT、DNT、DIT、ONT、DPT、PRT的正常取值范围在原型上有标注。
     */

    @Override
    public void task() {
        //每天凌晨1点处理昨日异常数据
        //查询昨日患者档案中无入院日期、手术时间的数据
        BaseDto<PmsArchivesDto.Query> baseDto = new BaseDto<>();
        PmsArchivesDto.Query query = new PmsArchivesDto.Query();
        query.setType((byte) 2);
        baseDto.setParam(query);
        baseDto.setPageNum(-1);
        PageInfo<PmsArchivesVo.Result> resultPageInfo = archivesService.listPmsArchives(baseDto);
        List<PmsArchivesVo.Result> resultList = resultPageInfo.getList();
        if (CollectionUtil.isNotEmpty(resultList)) {
            List<PmsArchivesVo.Result> collect = resultList.stream().filter(result -> result.getZllx() != null).collect(Collectors.toList());
            for (PmsArchivesVo.Result result : collect) {

                List<PmsArchivesVo.PmsArchivesRecordVo> recordVoList = result.getRecordVoList();
                Map<String, List<PmsArchivesVo.PmsArchivesRecordVo>> map = new HashMap<>();
                if (CollectionUtil.isNotEmpty(recordVoList)) {
                    map = recordVoList.stream().collect(Collectors.groupingBy(PmsArchivesVo.PmsArchivesRecordVo::getCode));
                }

                String zllx = result.getZllx();
                String[] split = zllx.split(",");
                for (String s : split) {
                    switch (s) {
                        //   治疗类型：静脉溶栓手术->开始静脉溶栓时间；
                        //    治疗类型：介入再通->穿刺完成时间；
                        //    治疗类型：脑出血手术->手术开始时间；
                        //    治疗类型：CEA/CAS手术->手术开始时间。
                        //（3）颅内血管检查方式（若患者治疗类型为颅内动脉瘤）
                        case "AIS静脉溶栓":
                            List<PmsArchivesVo.PmsArchivesRecordVo> jmrsTime = map.get(JMRS_TIME.getKey());
                            if (CollectionUtil.isEmpty(jmrsTime)) {
                                //添加异常项目
                                QuaAbnormalData quaAbnormalData = new QuaAbnormalData();
                                quaAbnormalData.setId(IdUtil.getSnowflake().nextId());
                                quaAbnormalData.setName(result.getName());
                                quaAbnormalData.setSex(result.getSex());
                                quaAbnormalData.setFileNum(result.getFileNum());
                                quaAbnormalData.setBlsId(result.getId());
                                quaAbnormalData.setHospitalizationNumber(result.getFileNum());
                                quaAbnormalData.setTreatmentType(zllx);
                                quaAbnormalData.setOperationName(result.getZllx());
                                quaAbnormalData.setDelFlag((byte) 0);
                                quaAbnormalDataMapper.insertSelective(quaAbnormalData);
                            }
                            break;
                        case "AIS介入再通":
                            List<PmsArchivesVo.PmsArchivesRecordVo> pmsArchivesRecordVos = map.get(ZL_JRZT_CCWCSJ.getKey());
                            if (CollectionUtil.isEmpty(pmsArchivesRecordVos)) {
                                //添加异常项目
                                QuaAbnormalData quaAbnormalData = new QuaAbnormalData();
                                quaAbnormalData.setId(IdUtil.getSnowflake().nextId());
                                quaAbnormalData.setBlsId(result.getId());
                                quaAbnormalData.setName(result.getName());
                                quaAbnormalData.setSex(result.getSex());
                                quaAbnormalData.setFileNum(result.getFileNum());
                                quaAbnormalData.setHospitalizationNumber(result.getFileNum());
                                quaAbnormalData.setTreatmentType(zllx);
                                quaAbnormalData.setOperationName(result.getZllx());
                                quaAbnormalData.setDelFlag((byte) 0);
                                quaAbnormalDataMapper.insertSelective(quaAbnormalData);
                            }
                            break;
                        case "脑出血":
                        case "CEA/CAS":
                            List<PmsArchivesVo.PmsArchivesRecordVo> sssjList = map.get(ZL_DML_SS_T.getKey());
                            if (CollectionUtil.isEmpty(sssjList)) {
                                //添加异常项目
                                QuaAbnormalData quaAbnormalData = new QuaAbnormalData();
                                quaAbnormalData.setId(IdUtil.getSnowflake().nextId());
                                quaAbnormalData.setBlsId(result.getId());
                                quaAbnormalData.setName(result.getName());
                                quaAbnormalData.setSex(result.getSex());
                                quaAbnormalData.setFileNum(result.getFileNum());
                                quaAbnormalData.setHospitalizationNumber(result.getFileNum());
                                quaAbnormalData.setTreatmentType(zllx);
                                quaAbnormalData.setOperationName(result.getZllx());
                                quaAbnormalData.setDelFlag((byte) 0);
                                quaAbnormalDataMapper.insertSelective(quaAbnormalData);
                            }
                        break;
                        default:
                            break;
                    }
                }
            }
        }

    }
}
